package com.nercel.dsj.gksales.exception;

import com.nercel.dsj.gksales.constant.Env;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author sunlin
 * @date 2018-10-31
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Value("${spring.profiles.active}")
    private String env;

    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ExceptionResultVO globalExceptionHandler(Exception e) {
//        if(!env.equals(Env.PROD)) {
//            e.printStackTrace();
//        }
        log.error(e.getMessage());
        e.printStackTrace();
        return new ResponseResultUtil().error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), env.equals(Env.PROD) ? null : e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ExceptionResultVO methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return new ResponseResultUtil().error(ResponseCode.ARGUMENT_NOTVALID_EXCEPTION.getCode(),
                e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler({RestApiException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ExceptionResultVO businessExceptionHandler(RestApiException e) {
        log.error(e.getCode() + " : " + e.getMessage());
        return new ResponseResultUtil().error(e.getCode(), e.getMessage());
    }

}
